# from app.common.setting import MINECRAFT_DIR,DONWLOAD_SOURCE
import os
from .download_file import DownloadManager
import aiohttp
import asyncio
import json
import requests
import re
import threading

DONWLOAD_SOURCE = 0
MINECRAFT_DIR = "C:\\.mineraft"


if DONWLOAD_SOURCE == 0:
    assetApi = "https://resources.download.minecraft.net"
elif DONWLOAD_SOURCE == 1:
    assetApi = "https://bmclapi2.bangbang93.com/assets"


class MinecraftVersionInstall:
    def install(
        self, version, jsonUrl, progress_callback, complete_callback, progress_callback1
    ):
        self.progress_callback = progress_callback
        self.progress_callback1 = progress_callback1
        self.complete_callback = complete_callback

        dir = os.path.join(MINECRAFT_DIR, "versions", version)
        jarDir = os.path.join(dir, version + ".jar")
        jsonDir = os.path.join(dir, version + ".json")
        url_path_pairs = []
        url_path_pairs.append(
            {"url": jsonUrl, "save_path": dir, "filename": str(version) + ".json"}
        )  # 主json文件

        json1 = requests.get(jsonUrl)
        json1 = json1.json()

        print(dir)
        urls = json1["downloads"]["client"]["url"]
        if DONWLOAD_SOURCE == 0:
            url_path_pairs.append(
                {"url": urls, "save_path": dir, "filename": str(version) + ".jar"}
            )  # 主jar文件
        elif DONWLOAD_SOURCE == 1:
            urls = "https://bmclapi2.bangbang93.com/version/" + version + "/client"
            url_path_pairs.append(
                {"url": urls, "save_path": dir, "filename": str(version) + ".jar"}
            )  # 主jar文件

        assetIndex = json1["assetIndex"]["url"]
        assetIndex = requests.get(assetIndex)
        assetIndex = assetIndex.json()
        for i_name, details in assetIndex["objects"].items():
            i_hash = details["hash"]
            # print(i_hash)
            hash = i_hash[:2]
            assetUrl = assetApi + "/" + hash + "/" + i_hash
            assetPath = MINECRAFT_DIR + "\\assets\\objects\\" + hash
            # print(assetUrl)
            # print("路径" + assetPath)
            url_path_pairs.append(
                {"url": assetUrl, "save_path": assetPath, "filename": i_hash}
            )

        libraries = json1["libraries"]
        # print(url_path_pairs)
        for library in libraries:
            artifact = library["downloads"]["artifact"]
            path = artifact["path"]
            url = artifact["url"]
            pattern = r"[^/]+$"
            match = re.search(pattern, path)
            if match:
                substring1 = match.group(0)
            last_slash_index = path.rfind("/")
            if last_slash_index != -1:
                substring = path[:last_slash_index]
            libassetPath = MINECRAFT_DIR + "\\libraries\\" + substring
            if DONWLOAD_SOURCE == 0:
                pass
            elif DONWLOAD_SOURCE == 1:
                url = url.replace(
                    "https://libraries.minecraft.net/",
                    "https://bmclapi2.bangbang93.com/maven/",
                )

            url_path_pairs.append(
                {"url": url, "save_path": libassetPath, "filename": substring1}
            )  # lib库文件

        self.downloader = DownloadManager(32)

        for item in url_path_pairs:
            url = item.get("url")
            save_path = item.get("save_path")
            filename = item.get("filename")
            if filename:
                # 如果存在 filename，则执行相关操作
                self.downloader.add_download_task(url, save_path, filename)
                # print(url)
            else:
                # 如果不存在 filename，则执行另一种操作
                self.downloader.add_download_task(url, save_path)
                # print(url)

        # 设置回调函数
        self.downloader.set_progress_callback(self.progress_callback)
        self.downloader.set_complete_callback(self.complete_callback)
        self.downloader.set_progress_callback1(self.progress_callback1)

        thread = threading.Thread(target=self.start_download_thread)
        thread.start()

        return 0

    def start_download_thread(self):
        try:
            asyncio.run(self.downloader.start_downloads())
        except Exception as e:
            print("下载停止：" + e)


# # 用于测试，需要实例化再传入版本和版本jsonUrl
# def progress_callback(a, progress):
#     print(f"下载进度: {progress}%")


# # 自定义所有任务完成回调函数
# def complete_callback(result):
#     if result is None:
#         print("完成")
#         pass


# def progress_callback1(progress):
#     pass


# d = MinecraftVersionInstall()
# back = d.install(
#     "1.21",
#     "https://piston-meta.mojang.com/v1/packages/177e49d3233cb6eac42f0495c0a48e719870c2ae/1.21.json",
#     progress_callback,
#     complete_callback,
#     progress_callback1,
# )
# print(back)  # 返回


# fetcher = MinecraftVersionFetcher()
# a = fetcher.out_versions(filter_type="release")
# print(a) 获取版本列表
